const fs = require('fs');
const path = require('path');



/**
 * 查找指定目录下所有文件
 * 
 * @param {String} directoryPath 目录绝对路径
 * @param {RegExp} filterRegex 过滤文件的正则表达式 可空
 * @param {Array} outputs 输入数组 可空
 */
exports.find = function find(directoryPath, filterRegex, outputs) {

    outputs = outputs || [];

    let names = fs.readdirSync(directoryPath);

    for (let i = 0, l = names.length; i < l; i++)
    {
        let name = names[i];
        let file = path.join(directoryPath, name);

        if (fs.statSync(file).isFile())
        {
            if (!filterRegex || filterRegex.test(file))
            {
                outputs.push(file);
            }
        }
        else
        {
            find(file, filterRegex, outputs);
        }
    }

    return outputs;
}


/**
 * 创建目录
 * 
 * @param {String} directoryPath 要创建的目录绝对路径
 */
exports.make = function make(directoryPath) {

    if (!fs.existsSync(directoryPath))
    {
        make(path.dirname(directoryPath));
        fs.mkdirSync(directoryPath);
    }
};


/**
 * 复制目录
 * 
 * @param {String} sourceDirectoryPath 源目录绝对路径
 * @param {String} outputDirectoryPath 输入目录绝对路径
 * @param {RegExp} exceptRegex 排除不复制文件的正则表达式 可空
 */
exports.copy = function copy(sourceDirectoryPath, outputDirectoryPath, exceptRegex) {

    let names = fs.readdirSync(sourceDirectoryPath);

    exports.make(outputDirectoryPath);

    for (let i = 0, l = names.length; i < l; i++)
    {
        let name = names[i];
        let source = path.join(sourceDirectoryPath, name);
        let target = path.join(outputDirectoryPath, name);

        if (fs.statSync(source).isFile())
        {
            if (!exceptRegex || !exceptRegex.test(target))
            {
                fs.copyFileSync(source, target);
            }
        }
        else
        {
            copy(source, target);
        }
    }
};


/**
 * 清除目录
 * 
 * @param {String} directoryPath 要清除的目录绝对路径
 */
exports.clean = function clean(directoryPath) {

    if (fs.existsSync(directoryPath))
    {
        if (fs.statSync(directoryPath).isFile())
        {
            fs.unlinkSync(directoryPath);
        }
        else
        {
            let files = fs.readdirSync(directoryPath);

            for (let i = 0, l = files.length; i < l; i++)
            {
                clean(path.join(directoryPath, files[i]));
            }
        
            fs.rmdirSync(directoryPath);
        }
    }
};
